package com.yhx.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyFileUtils {
    /**
     * 文件下载
     * @param fileName
     * @param path
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> download(String fileName, String path) throws IOException {
        //找到需要下载的文件
        File file = new File(path + fileName);
        //把文件读到内存
        byte[] bytes = FileUtils.readFileToByteArray(file);
        //在设置状态吗
        HttpStatus ok = HttpStatus.OK;
        //响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置为二进制文件，支持所有文件类型
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //设置弹框   设置下载的文件名
        httpHeaders.setContentDispositionFormData("attachment",new String(fileName.getBytes("utf-8"),"iso-8859-1"));
        return new ResponseEntity<>(bytes,httpHeaders,ok);
    }
    /**
     * 文件下载 默认下载在E:/upload/
     * @param fileName
     * @return
     * @throws IOException
     */
    public static ResponseEntity<byte[]> download(String fileName) throws IOException {
        String path="E:/upload/";
        return download(fileName,path);
    }

    /**
     * 文件上传
     * @param multipartFile
     * @param path
     * @return
     */
    public static File upload(MultipartFile multipartFile, String path){
        //改名字
        String filename = createFileName(multipartFile.getOriginalFilename());
        //执行上传
        try {
            File file = new File(path + filename);
            multipartFile.transferTo(file);
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 文件上传  默认上传到 E:/upload/pic/
     * @param multipartFile
     * @return
     */
    public static File upload(MultipartFile multipartFile){
        String path="E:/upload/pic/";
        return upload(multipartFile,path);
    }
    /**
     * 生成文件名
     * @param oldName
     * @return
     */
    private static String createFileName(String oldName){
        int index = oldName.lastIndexOf(".");
        String suffixName = oldName.substring(index);
        String format = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String substring = String.valueOf(Math.random()).substring(2, 6);
        return format+substring+suffixName;
    }

}
